package xuperchain

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

type ViewRecord struct {
	UserId   string `json:"userId"`
	ViewDate string `json:"viewDate"`
}

func GetViewUserIds(papername string, username string, page int, pageSize int) (int, []string, []string, error) {
	type ListLengthResponse struct {
		Length string `json:"0"`
	}
	account, err := account.GetAccountFromFile(path, pwd)
	if err != nil {
		panic(err)
	}
	fmt.Printf("privatekey Account address: %v\n", account.Address)

	err = account.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	xchainClient, err := xuper.New(nodeAddress)
	if err != nil {
		panic(err)
	}
	contractName := "xc_filestorage8"
	//获取访问记录长度
	args := map[string]string{
		"_name":     papername,
		"_operator": username,
	}

	txgetUserIdsLength, err := xchainClient.QueryEVMContract(account, contractName, "getUserIdsLength", args)
	if err != nil {
		return 0, nil, nil, err
	}
	fmt.Printf("addViewRecord SUCCESS! Response: %s\n", txgetUserIdsLength.ContractResponse.Body)
	var response []ListLengthResponse
	err = json.Unmarshal([]byte(txgetUserIdsLength.ContractResponse.Body), &response)
	if err != nil {
		panic(err)
	}
	var totalFiles int
	// 确保解析出来的数组中有一个元素
	if len(response) > 0 {
		totalFiles, err = strconv.Atoi(response[0].Length)
		if err != nil {
			panic(err)
		}
	} else {
		panic("No data returned")
	}
	startIndex := (page - 1) * pageSize
	if startIndex >= totalFiles {
		return 0, nil, nil, fmt.Errorf("startIndex out of bounds")
	}

	endIndex := startIndex + pageSize
	if endIndex > totalFiles {
		endIndex = totalFiles
	}

	var userNames []string
	var times []string

	txGetUserIdsAtIndexargs := map[string]string{
		"_name":     papername,
		"_operator": username,
		"index":     "1",
	}
	txGetUserIdsAtIndex, err := xchainClient.QueryEVMContract(account, contractName, "getUserIdsAtIndex", txGetUserIdsAtIndexargs)
	if err != nil {
		fmt.Println(err)
		return 0, nil, nil, err
	}

	jsonStr := string(txGetUserIdsAtIndex.ContractResponse.Body)

	// 清理 JSON 字符串
	cleanedJsonStr := strings.Trim(jsonStr, "[]")
	cleanedJsonStr = strings.Replace(cleanedJsonStr, "\\\"", "", -1)
	cleanedJsonStr = strings.Replace(cleanedJsonStr, "{\"0\":\"", "", -1)
	cleanedJsonStr = strings.Replace(cleanedJsonStr, "\"}", "", -1)

	records := strings.Split(cleanedJsonStr, "},{")

	for _, record := range records {
		// 清理每个记录字符串
		record = strings.Trim(record, "{}")

		// 分割键值对
		parts := strings.Split(record, ",")
		// 提取 userId 和 viewDate
		userId := strings.Split(parts[0], ":")[1]
		viewDate := strings.Join(parts[1:len(parts)-1], ",")
		viewDate = strings.Split(viewDate, ":")[1] + ":" + strings.Split(viewDate, ":")[2] + ":" + strings.Split(viewDate, ":")[3]

		// 检查 userId 是否已存在
		userIdIndex := -1
		for i, id := range userNames {
			if id == userId {
				userIdIndex = i
				break
			}
		}

		if userIdIndex != -1 {
			// 如果 userId 已存在，则更新 viewDate
			times[userIdIndex] = viewDate
		} else {
			// 如果 userId 不存在，则添加新的 userId 和 viewDate
			userNames = append(userNames, userId)
			times = append(times, viewDate)
		}
		// 打印结果
		fmt.Printf("UserID: %s, ViewDate: %s\n", userId, viewDate)
	}

	return totalFiles, userNames, times, nil
}
